package com.zzy.service.impl;

import com.zzy.dao.BaseDao;
import com.zzy.model.CompleteParams;
import com.zzy.model.FlowStep;
import com.zzy.model.User;
import com.zzy.service.FlowService;
import com.zzy.service.FlowStepService;

import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**流程走过的节点
 *  @Author zzy
 *  @Time 2018年11月21日14:12:26
 */
@Transactional
@Service()
public class FlowStepServiceImpl implements FlowStepService {

    @Autowired
    private BaseDao<FlowStep> basedao;

    @Autowired
    private FlowService flowService;

    public FlowStep getUnique(String hql, Object[] param) {
        return basedao.get(hql,param );
    }

    public FlowStep getByID(String id) {
        return basedao.get(FlowStep.class,id );
    }

    public List<FlowStep> getList(String hql, Object[] param) {
        return  basedao.find(hql,param );
    }

    public List<FlowStep> getListByProId(String proId) {
        if(StringUtils.hasText(proId)){
            return  basedao.find(" from FlowStep where proId = ? ", new Object[]{proId} );
        }
        return  null;

    }

    public String save(CompleteParams params) {//, FlowStep model

        Assert.isTrue(StringUtils.hasText(params.getProcInsId()), "流程ID不能为空");
        Assert.isTrue(StringUtils.hasText(params.getStepCode()), "任务编码不能为空");

        //根据流程ID获取该流程下的 所经过的节点list
        List<FlowStep> actTasks = getListByProId(params.getProcInsId());

        if( actTasks!=null&&!actTasks.isEmpty() ){//以前有 过节点
            FlowStep lastActTask = actTasks.get(actTasks.size()-1);

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            User user2 = (User)request.getSession().getAttribute("user");

            Task task=flowService.getNextTask(params.getProcInsId(), user2.getId());

            String keyString = task.getTaskDefinitionKey();//当前环节ID
            String code = lastActTask.getNodeId();//历史表中最后一条数据环节ID
            if(code.equals(keyString)){
                return lastActTask.getId();
            }
        }
        //新的流程

        FlowStep model = new FlowStep();
        model.setFlowDepId(params.getProcInsId());
        model.setFormId(params.getStiId());
        model.setNodeId(params.getStepCode());
        model.setNodeName(params.getStepName());
        model.setState(StringUtils.hasText(params.getApprove())?params.getApprove():"y");
        String auditor = params.getAuditor();//这里是配置 候选审批人
        if(StringUtils.hasText(auditor)){//把 候选审批人 放到，节点流程表中
            model.setAuditor(auditor);
        }
        basedao.save(model);
        if(model.getId()!=null){
           return   model.getId();
        }else{
            return "";
        }



    }

    public Integer save(FlowStep model) {
        int i = 1;
        try {
            basedao.save(model);
        } catch (Exception e) {
            i = -1;
        }
        return i;
    }


    public Integer del(String id) {
        int i = 1;
        try {
            if (StringUtils.hasText(id)){
                FlowStep o = new FlowStep();
                o=this.getByID(id);
                basedao.delete(o);
            }
        } catch (Exception e) {
            i = -1;
        }
        return i;
    }


    public Integer delByProId(String proId) {

        int i = 1;
        try {
            if (StringUtils.hasText(proId)){
                //安全限制，防止 proId 注入
                proId = proId.replaceAll("\'","");
                // 如果安全过不去，可以把 flowNodeAuditService 注入过来
                String sql = " DELETE s,a FROM flow_node_step s "
                        + " LEFT JOIN flow_node_audit a ON s.id = a.step_id "
                        + " WHERE step.pro_id = '"+proId+"' ";
                basedao.executeSql(sql);//执行删除
            }
        } catch (Exception e) {
            i = -1;
        }
        return i;


    }


    public Integer update(FlowStep model) {
        int i = 1;
        try {
            basedao.update(model);
        } catch (Exception e) {
            i = -1;
        }
        return i;
    }

    public Integer saveOrUpdate(FlowStep model) {
        int i = 1;
        try {
            basedao.saveOrUpdate(model);
        } catch (Exception e) {
            i = -1;
        }
        return i;
    }

    public String find(String procInsId, String activitiId) {
       /* //获取activitiId最后操作信息
        List<ActTask> list = actTaskDao.findActTask(procInsId,activitiId);
        ActTask actTask = list.get(0);
        List<ActTaskReview> list2 = actTaskDao.findActTaskReview(actTask.getId());
        ActTaskReview actTaskReview = list2.get(0);
        String files = actTaskReview.getFiles();
        List<String> file = Arrays.asList(files.split(","));
        String fString =  file.get(3);*/
        return "";
    }

}
